import sys, os
sys.path.append(os.pardir)
import numpy as np
import pickle
from PIL import Image

from dataset.mnist import load_mnist

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def identity_function(x):
    return x

def img_show(img):
    pil_img = Image.fromarray(np.uint8(img))
    pil_img.show()

def get_data():
    (x_train,t_train) , (x_test,t_test) = load_mnist(normalize=True,flatten=True,one_hot_label=False)
    return (x_test,t_test)
# 如果normalize不为True则运行时sigmoid函数会报溢出错误
# 这样把数据限定到某个范围内的处理称为正规化（normalization）。此外，对神经网络的输入数据
# 进行某种既定的转换称为预处理（pre-processing）。
def init_network():
    with open("sample_weight.pkl",'rb') as f:
        network = pickle.load(f)
    return network

def predict(network,x):
    W1, W2, W3 = network['W1'], network['W2'], network['W3']

    b1, b2, b3 = network['b1'], network['b2'], network['b3']

    a1 = np.dot(x, W1) + b1
    z1 = sigmoid(a1)

    a2 = np.dot(z1, W2) + b2
    z2 = sigmoid(a2)

    a3 = np.dot(z2, W3) + b3
    y = identity_function(a3)
    return y

# 读入数据并显示图像
# (x_train,t_train),(x_test,t_test) = load_mnist(flatten=True,normalize=False)
# img = x_train[0]
# label = t_train[0]
# # print(label)
# # print(x_train.shape)
# img = img.reshape(28,28)
# img_show(img)

# 计算神经网络的精确度
# x,t = get_data()
# network = init_network()
# accuracy_cnt = 0
# for i in range(len(x)):
#     y = predict(network,x[i])
#     p = np.argmax(y)
#     if p == t[i]:
#         accuracy_cnt+=1
#
# print("Accuracy:{}".format(float(accuracy_cnt) / len(x)))

# 查看神经网络的权重维数
# x,_ = get_data()
# network = init_network()
# W1, W2, W3 = network['W1'], network['W2'], network['W3']
# print(x.shape)
# print(x[0].shape)
# print(W1.shape)
# print(W2.shape)
# print(W3.shape)

# 对神经网络进行批处理
x,t = get_data()
network = init_network()
batch_size = 100
accuracy_cnt = 0

for i in range(0,len(x),batch_size):
    x_batch = x[i:i+batch_size]
    y_batch = predict(network,x_batch)
    p = np.argmax(y_batch,axis=1)
    accuracy_cnt+=np.sum(p==t[i:i+batch_size])

print("Accuracy:{}".format(float(accuracy_cnt) / len(x)))